import React, {useEffect} from 'react'
import type { NextPage, GetServerSideProps } from 'next'
import Link from 'next/link'
import Image from 'next/image'
import {useSelector, useDispatch} from 'react-redux'
import {getUserData, useSliceName, addCount, reduceCount} from '@redux/slice/user'
import {UserStore} from '@redux/ts/slice/user'
import {getUser} from '@request/user'
import styles from '../styles/Home.module.css'
import {HomeProps} from '@interface/home/index'
import Sse from '@components/webSocket/sse'

const Home = (props: HomeProps) => { // NextPage
  const dispatch = useDispatch()
  const useStore = useSelector((state: {[useSliceName]: UserStore}) => {
    return state[useSliceName]
  })

  // 根据数组创建jsx
  const createDom = (obj: Data) => {
    return React.createElement(
      'div',
      { key: obj.id },
      ...[obj.age, obj.name]
    )
  }

  useEffect(() => {
    // 初始化获取用户信息
    dispatch( getUserData() )
  }, [])
  
  return (
    <div className={styles.container}>
      <main className={styles.main}>
        <div className='testDivStyle'>中间显示区域</div>
        <div>
          用户名称：
          {/* {JSON.stringify(useStore.user)} */}
          {
            useStore.user.map((item: Data) => <span key={item.id}>{item.name} - {item.age} </span>)
          }
          {createDom({name: 'test', id: '78', age: 2023})}
          {props.chil}
        </div>
        <div>
          <button onClick={() => dispatch(addCount(5))}>+</button>
          count: {useStore.count}
          <button onClick={() => dispatch(reduceCount(3))}>-</button>
        </div>
        <div className={styles.media_test}>
          media 测试
        </div>
        <Sse />
      </main>

      <footer className={styles.footer}>
        底部
      </footer>
    </div>
  )
}

export default Home


// 动态数据
export const getServerSideProps: GetServerSideProps = async (context) => {
  // 路由信息
  const params = context.params
  let userData: HomeDTSProps['UserData'] = {code: 0, data: []}
  try {
    userData = await getUser({url: "http://localhost:3535/user/getUser"}).then(data => data.json())
  } catch (error) {
    
  }

  const list: () => JSX.Element = () => (
    <ul>
      {
        userData.data.map((item: Data) => (
          <li key={item.id}>{item.name} - {item.age}</li>
        ))
      }
    </ul>
  )
  
  return {
    props: {
      userData: userData.data,
      chil: '<>123 getServerSideProps </>'
    }
  }
}